package com.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class TokenUpdateService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;

    /**
     * 第一次执行是启动tomcat后2毫秒就执行，以后每隔30分钟执行一次
     */
    @Scheduled(initialDelay = 2,fixedRate = 18000)
    public void updateToken(){
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String newUrl=String.format(url,appid,secret);
        String result=restTemplate.getForObject(newUrl,String.class);
        System.out.println(result);

        String token= JSONObject.parseObject(result).getString("access_token");
        redisTemplate.boundValueOps("token").set(token);
    }

}
